from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from utils.authentication import CustomJWTAuthentication
from .models import ChatRoom, ChatRoomMember, ChatMessage, MessageReadStatus
from Login.models import User, ThirdPartyAccount
from django.db.models import Q

class ChatRoomListView(APIView):
    """获取用户的聊天室列表"""
    authentication_classes = [CustomJWTAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = request.user
        chat_rooms = ChatRoomMember.objects.filter(user=user).select_related('room')
        room_list = []
        for member in chat_rooms:
            room = member.room
            last_message = room.messages.order_by('-created_at').first()
            other_user = None
            if room.room_type == 'private':
                other_member = ChatRoomMember.objects.filter(room=room).exclude(user=user).first()
                if other_member:
                    other_user = self.get_user_info(other_member.user)
            # 新增member_ids
            member_ids = list(ChatRoomMember.objects.filter(room=room).values_list('user_id', flat=True))
            # 新增members详细信息
            members_info = []
            for m in ChatRoomMember.objects.filter(room=room):
                members_info.append(self.get_user_info(m.user))
            room_data = {
                'id': room.id,
                'name': room.name or (other_user.get('nickname', '') if other_user else ''),
                'room_type': room.room_type,
                'created_at': room.created_at,
                'updated_at': room.updated_at,
                'last_message': {
                    'content': last_message.content if last_message else '',
                    'message_type': last_message.message_type if last_message else 'text',
                    'created_at': last_message.created_at if last_message else None,
                    'sender_id': last_message.sender.id if last_message else None,
                } if last_message else None,
                'other_user': other_user,
                'member_count': ChatRoomMember.objects.filter(room=room).count(),
                'member_ids': member_ids,
                'members': members_info  # 新增字段
            }
            room_list.append(room_data)
        room_list.sort(key=lambda x: x['last_message']['created_at'] if x['last_message'] else x['created_at'], reverse=True)
        return Response({'code': 200, 'rooms': room_list})

    def get_user_info(self, user):
        try:
            third_party = ThirdPartyAccount.objects.get(user=user, provider='dingtalk')
            return {
                'id': user.id,
                'nickname': third_party.nickname or user.phone,
                'avatar': third_party.avatar_url or ''
            }
        except ThirdPartyAccount.DoesNotExist:
            return {
                'id': user.id,
                'nickname': user.phone,
                'avatar': ''
            }

class CreateChatRoomView(APIView):
    """创建群聊/私聊"""
    authentication_classes = [CustomJWTAuthentication]
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user_ids = request.data.get('user_ids')
        room_type = request.data.get('room_type', 'private')
        room_name = request.data.get('room_name', '')
        if not user_ids or len(user_ids) < 2:
            return Response({'code': 400, 'msg': '用户ID列表不能为空且至少两人'}, status=400)

        # 强制类型转换和排序，查找所有成员完全一致的房间（不区分room_type）
        sorted_ids = sorted([int(uid) for uid in user_ids])
        candidate_rooms = ChatRoom.objects.all()
        for room in candidate_rooms:
            members = list(room.members.values_list('user_id', flat=True))
            if sorted(members) == sorted_ids:
                return Response({'code': 200, 'room_id': room.id, 'msg': '聊天室已存在'})

        # 没有则新建
        room = ChatRoom.objects.create(room_type=room_type, name=room_name)
        for uid in user_ids:
            try:
                user = User.objects.get(id=uid)
                ChatRoomMember.objects.create(room=room, user=user)
            except User.DoesNotExist:
                continue
        return Response({'code': 200, 'room_id': room.id, 'msg': '房间创建成功'})

class SearchUsersView(APIView):
    """搜索用户"""
    authentication_classes = [CustomJWTAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = request.user
        keyword = request.GET.get('keyword', '').strip()
        if not keyword:
            return Response({'code': 400, 'msg': '缺少搜索关键词'}, status=400)
        users = User.objects.filter(Q(phone__icontains=keyword)).exclude(id=user.id)[:10]
        user_list = []
        for user_obj in users:
            user_list.append({
                'id': user_obj.id,
                'nickname': user_obj.phone,
                'avatar': ''
            })
        return Response({'code': 200, 'users': user_list})

class ChatMessageListView(APIView):
    """获取聊天室历史消息"""
    authentication_classes = [CustomJWTAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = request.user
        room_id = request.GET.get('room_id')
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 20))

        if not room_id:
            return Response({'code': 400, 'msg': '缺少聊天室ID'}, status=400)

        if not ChatRoomMember.objects.filter(room_id=room_id, user=user).exists():
            return Response({'code': 403, 'msg': '您不是该聊天室成员'}, status=403)

        messages = ChatMessage.objects.filter(room_id=room_id).order_by('-created_at')
        start = (page - 1) * page_size
        end = start + page_size
        messages = messages[start:end]

        message_list = []
        for message in reversed(messages):  # 正序
            sender = message.sender
            try:
                third_party = ThirdPartyAccount.objects.get(user=sender, provider='dingtalk')
                nickname = third_party.nickname or sender.phone
                avatar = third_party.avatar_url or ''
            except ThirdPartyAccount.DoesNotExist:
                nickname = sender.phone
                avatar = ''
            message_list.append({
                'id': message.id,
                'content': message.content,
                'message_type': message.message_type,
                'file_url': message.file_url,
                'created_at': message.created_at,
                'sender': {
                    'id': sender.id,
                    'nickname': nickname,
                    'avatar': avatar
                },
                'room_id': room_id
            })

        return Response({
            'code': 200,
            'messages': message_list,
            'has_more': len(message_list) == page_size
        })

class SendMessageView(APIView):
    """发送消息到聊天室"""
    authentication_classes = [CustomJWTAuthentication]
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user = request.user
        room_id = request.data.get('room_id')
        content = request.data.get('content', '').strip()
        message_type = request.data.get('message_type', 'text')
        file_url = request.data.get('file_url', '')

        if not room_id or not content:
            return Response({'code': 400, 'msg': '缺少参数'}, status=400)

        if not ChatRoomMember.objects.filter(room_id=room_id, user=user).exists():
            return Response({'code': 403, 'msg': '您不是该聊天室成员'}, status=403)

        message = ChatMessage.objects.create(
            room_id=room_id,
            sender=user,
            content=content,
            message_type=message_type,
            file_url=file_url
        )
        # 可选：此处可通过channels层主动推送WebSocket消息
        return Response({'code': 200, 'msg': '发送成功', 'message_id': message.id})

class MarkMessagesReadView(APIView):
    """标记消息为已读"""
    authentication_classes = [CustomJWTAuthentication]
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user = request.user
        message_ids = request.data.get('message_ids', [])

        if not message_ids:
            return Response({'code': 400, 'msg': '缺少消息ID列表'}, status=400)

        for message_id in message_ids:
            try:
                message = ChatMessage.objects.get(id=message_id)
                if message.sender.id != user.id:
                    MessageReadStatus.objects.get_or_create(
                        message=message,
                        user=user
                    )
            except ChatMessage.DoesNotExist:
                continue

        return Response({'code': 200, 'msg': '标记成功'})

# 未来可能用到的房间/用户管理相关接口可在此处保留或补充
